package com.jack.xmlparser.parser;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.util.Xml;

import com.jack.xmlparser.iui.BaseParser;
import com.jack.xmlparser.util.Book;

public class PullParserForBook implements BaseParser {

	private List<Object> mBooks;
	private Book mBook;
	
	@Override
	public List<Object> parserToObject(InputStream is) {
		// TODO Auto-generated method stub
		try {
			XmlPullParser mParser = Xml.newPullParser();
			mParser.setInput(is, "UTF-8");
			
			int mEventType = mParser.getEventType();
			while (mEventType != XmlPullParser.END_DOCUMENT) {
				switch (mEventType) {
				case XmlPullParser.START_DOCUMENT:
					mBooks = new ArrayList<Object>();
					break;
				case XmlPullParser.START_TAG:
					if (mParser.getName().equals("book")) {
						mBook = new Book();
						if (mParser.getAttributeCount() > 0) {
							for (int i = 0; i < mParser.getAttributeCount(); i++) {
								if (mParser.getAttributeName(0).equals("id")) {
									mBook.setId(Integer.parseInt(mParser.getAttributeValue(0)));
									break;
								}
							}
						}
					}  else if (mParser.getName().equals("name")) {
						mEventType = mParser.next();
						mBook.setName(mParser.getText());
					} else if (mParser.getName().equals("price")) {
						mEventType = mParser.next();
						mBook.setPrice(Float.parseFloat(mParser.getText()));
					}
					break;
				case XmlPullParser.END_TAG:
					if (mParser.getName().equals("book")) {
						mBooks.add(mBook);
						mBook = null;
					}
					break;
				}
				mEventType = mParser.next();
			}
			return mBooks;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			mBooks = null;
			return null;
		}
	}

	@Override
	public String parserToXml(List<Object> list) {
		// TODO Auto-generated method stub
		try {
			XmlSerializer mSerializer = Xml.newSerializer();
			StringWriter mWriter = new StringWriter();
			mSerializer.setOutput(mWriter);
			mSerializer.startDocument("UTF-8", true);
			mSerializer.startTag("", "books");
			for (Object o : list) {
				if (o instanceof Book) {
					Book mBook = (Book) o;
					mSerializer.startTag("", "book");
					mSerializer.attribute("", "id", String.valueOf(mBook.getId()));
					
					mSerializer.startTag("", "name");
					mSerializer.text(mBook.getName());
					mSerializer.endTag("", "name");
					
					mSerializer.startTag("", "price");
					mSerializer.text(String.valueOf(mBook.getPrice()));
					mSerializer.endTag("", "price");
					
					mSerializer.endTag("", "book");
				}
			}
			mSerializer.endTag("", "books");
			mSerializer.endDocument();
			
			return mWriter.toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}

}
